<style lang="stylus">
.home
  min-height 100%
  overflow hidden
  padding-top 248px
  &.main-channel
    padding-bottom 140px
  .top-header
    padding-top 90px
    box-sizing border-box
    width 100%
    background url("../assets/index/index_header_03.jpg") no-repeat
    background-size cover
    height 248px
    position fixed
    top 0
    z-index 3
    max-width 750px;/*no*/
    margin 0 auto
  .portals
    overflow-x scroll
    overflow-y hidden
    -webkit-overflow-scrolling touch
    display -webkit-box
    -webkit-box-align center
  .channel-entrance
    background url("../assets/index/index01.png") no-repeat center
    background-size 33px
    width 33px
    height 33px
  .full-icon
    background url("../assets/index/index01.png") no-repeat center
    background-size 33px
    width 72px
    height 45px
    right 0
    top 50%
    transform translateY(-50%)
  .portal
    white-space nowrap
    & + .portal
      margin-left 48px
  .module-cover
    background-size cover
  .module.app-module
    width 25%
    .module-cover
      width 80px
      height 80px
      margin auto
  .module-more
    background url("../assets/index/right_arrow_gray.png") no-repeat right 9px
    background-size 13px 26px
  .module-icon
    height 28px
  .swiper-container
    height calc(0.5291 * 100vw)
    max-height 400px
  .swiper-wrapper
    height 100%
  .swiper-slide
    width 100%
    height 100%
    background-size cover
    background-position center
    background-image url("../assets/landscape_default.png")
    max-width 750px;/*no*/
    &::after
      position absolute
      left 0
      bottom 0
      display inline-block
      content ''
      width 100%
      height 150px
      background linear-gradient(0, rgba(0, 0, 0, 0.8), rgba(0, 0, 0, 0.3) 60%, transparent)
      z-index 1
  .swiper-pagination-bullets
    position absolute
    right 20px
    bottom 20px
    left auto
    transform translateX(0)
    text-align right
  .swiper-pagination-bullet
    background #ddd
    width 10px
    height 5px
    border-radius 3px
    opacity 1
    margin-left 10px
  .swiper-pagination-bullet-active
    background #7461ff
  .banner-overlay
    top 0
    left 0
    width 100%
    height 100%
  .banner-title
    bottom 14px
    left 20px
    z-index 3
  .search-input-wrapper
    height 64px
    border-radius 30px
    background-color #3e368f
    &::before
      content ''
      display block
      width 32px
      height 33px
      background url("../assets/search/icon_search.png") no-repeat left center
      background-size cover
  .search-input
    border 0
    background-color transparent
    margin-left 10px
    line-height 72px
    height 64px
    width 90%
    display block
    color #afabd2
  .collect
    width 60px
    height 60px
    background url("../assets/index/index_collect.png") no-repeat
    background-size cover
  .history
    width 60px
    height 60px
    background url("../assets/index/index_history.png") no-repeat
    background-size cover
  .overflow-x
    overflow-x scroll
  .app-divider
    top 50%
    background-color #eee
    width 100%
    height 2px
  .mint-popup
    width 80%
    height 100%
    padding 130px 30px 0
  .channel
    width calc((100% - 36px) / 3)
    height 194px
    position relative
    background-color #f7f7f7
    border-radius 6px
    &:not(:nth-child(3n + 1))
      margin-left 18px
    img
      position absolute
      top 60%
      left 50%
      transform translate3d(-50%, -50%, 0)
      width auto
      height auto
      max-height 36%
      max-width 36%
    .channel-name
      color #7b7b7b
  .back
    position absolute
    padding-left 30px
    background url("../assets/search/icon_back.png") no-repeat left center
    background-size 16px 29px
    width 72px
    height 45px
    left 30px
    top 50%
    transform translateY(-50%)
</style>

<template lang="pug">
.home(:class="{main: isHome, 'main-channel': isMainChannel}")
  .top-header
    .portal-wrapper.flex(v-if="isHome")
      .channel-entrance.pdl-50.pdr-50(@click="onOpenSideBar")
      .portals.fz-32.mgl-22
        .portal.white(v-for="(keyword, index) in keywords", :key="index", :class="{bold: index === keywordIndex}",
          @click="onSelectKeyword(index)") {{keyword.title}}
    .title-bar.center.relative(v-else)
      .back.fz-34.white(@click="onBack", v-if="!isMainChannel")
      .fz-32.white.bold {{topTitle}}
      .full-icon.absolute(@click="onFullFilm")
    .mgt-24.flex.pdl-30.pdr-14
      .search-input-wrapper.flex.pdh-30.flex-1
        .search-input.fz-28.white(@click="onLinkPage('search')") {{hotKeyword || '输入您想找的影片名称'}}
      .collect.mgl-18(@click="goHistory('favor')")
      .history.mgl-18(@click="goHistory('history')")
  swiper(:options="swiperOption", v-if="portal.banners.length")
    swiper-slide.relative(v-for="(banner, index) in portal.banners", :key="banner.id", :style="{backgroundImage: `url(${getImage(banner.cover)})`}")
      .banner-overlay.absolute(@click="onItemDispatch(banner)")
      .banner-title.fz-30.bold.white.absolute {{banner.title}}
    .swiper-pagination(slot='pagination')
  .mgt-34(v-for="(module, index) in portal.modules", :key="index", :class="{'pdb-30': module.style === 3}")
    .flex.pdl-20.pdr-24.fz-30(@click="onModuleMore(module)")
      img.module-icon(:src="getImage(module.cover)")
      .black-33.bold.mgl-14 {{module.title}}
      template(v-if="module.more")
        .flex-1
        .black-33.module-more.pdr-20 更多
    .flex.mgt-30(:class="module.style === 3 ? 'overflow-x': 'flex-wrap'")
      film-card(v-for="(item, innerIndex) in module.data", :key="item.id", :film="item", :type="module.style", :index="innerIndex")
  .mgt-34(v-if="isHome && portal.apps.length")
    .flex.pdl-20.pdr-24.fz-30
      img.module-icon(src="../assets/index/vip_hot_icon.png")
      .black-33.bold.mgl-14 八大VIP免费看
      .flex-1
    .flex.flex-wrap.relative
      .app-divider.absolute
      .module.center.flex-col.app-module.pdb-28.mgt-30(v-for="(app, index) in portal.apps", :key="index", @click="onAppDispatch(app)")
        .module-cover(:style="{backgroundImage: `url(${getImage(app.icon)})`}")
        .pdh-20.mgt-20 {{app.title}}
  no-more(v-if="loadDone")
  tabs(v-if="isMainChannel", :selected="selectedTab")
  popup(position="left", v-model="showSideBar")
    .fz-32.bold 常用频道
    .mgt-30.flex.flex-wrap
      .channel.mgt-18(v-for="(channel, index) in channels", :key="index", @click="onLinkToChannel(channel)")
        img(:src="getImage(channel.cover)")
        .channel-name.fz-28.center.pdt-24 {{channel.title}}
</template>

<script>
import { Popup } from 'mint-ui'
import { swiper, swiperSlide } from 'vue-awesome-swiper'
import { CHANNEL, FILM_TYPE, CACHE_KEY, ACTION_TYPE } from '../const'
import Tabs from '../components/Tabs.vue'
import NoMore from '../components/NoMore.vue'
import FilmCard from '../components/FilmCard.vue'

export default {
  name: 'home',
  components: {
    Tabs, NoMore, FilmCard, Popup, swiper, swiperSlide
  },
  data: () => ({
    pageTitle: '首页',
    keywords: [],
    keywordIndex: 0,
    portal: {
      banners: [],
      modules: [],
      apps: []
    },
    hots: [],
    selectedTab: CHANNEL.RECOMMEND,
    isHome: false,
    topTitle: '',
    loadDone: false,
    showSideBar: false,
    channels: [],
    hotKeyword: '',
    hotKeywordIndex: 0,
    isMainChannel: true,
    swiperOption: {
      pagination: {
        el: '.swiper-pagination'
      },
      direction: 'horizontal',
      autoplay: true,
      loop: true
    }
  }),

  watch: {
    '$route.query.id': function () {
      this.routeChangeData()
    }
  },

  mounted() {
    this.routeChangeData()
    this.$get('portal/channels').then(channels => {
      this.channels = channels
      if (this.isMainChannel && !this.topTitle) {
        this.topTitle = this.getChannelName()
      }
    })
  },

  methods: {
    checkHotKeyword() {
      if (this.portal.searchKeywords && this.portal.searchKeywords.length > 0) {
        this.hotKeyword = `大家都在看“${this.portal.searchKeywords[this.hotKeywordIndex++].keyword}”`
        if (this.hotKeywordIndex >= this.portal.searchKeywords.length) {
          this.hotKeywordIndex = 0
        }
        setTimeout(this.checkHotKeyword.bind(this), 2000)
      }
    },

    routeChangeData() {
      this.hotKeywordIndex = 0
      this.selectedTab = +this.$route.query.id || CHANNEL.RECOMMEND
      this.isHome = this.selectedTab === CHANNEL.RECOMMEND
      this.isMainChannel = this.selectedTab === CHANNEL.RECOMMEND ||
          this.selectedTab === CHANNEL.MOVIE || this.selectedTab === CHANNEL.SERIES

      // 设置顶部title
      if (this.selectedTab === CHANNEL.MOVIE) {
        this.topTitle = '电影'
      } else if (this.selectedTab === CHANNEL.SERIES) {
        this.topTitle = '电视剧'
      } else if (this.isHome) {
        this.topTitle = ''
      } else {
        this.topTitle = this.getChannelName()
      }

      if (this.isHome) {
        this.loadKeywords()
      }
      this.loadPortalData()
    },

    onSelectKeyword(index) {
      this.keywordIndex = index
      this.onItemDispatch(this.keywords[this.keywordIndex])
    },

    loadKeywords() {
      this.keywords = this.getStore(CACHE_KEY.HOME_TOP_KEYWORDS) || []
      this.$get('portal/recmd/keyword').then(keywords => {
        this.keywords = [{
          type: ACTION_TYPE.LINK,
          params: '/home',
          title: '精选'
        }].concat(keywords)
        this.saveStore(CACHE_KEY.HOME_TOP_KEYWORDS, this.keywords)
      })
    },

    loadPortalData() {
      this.loadDone = false
      this.$get('portal/index', { id: this.selectedTab }).then(portal => {
        this.portal = portal
        this.loadDone = true

        // 存储供搜索页面使用
        this.saveStore(CACHE_KEY.HOT_KEYWORDS, portal.searchKeywords || [])
        this.checkHotKeyword()
      })
    },

    onFullFilm() {
      const channel = this.portal.params
      this.onFilmList(channel, `全部${this.topTitle}`)
    },

    onModuleMore({ more, id, title }) {
      if (more) {
        this.$router.push({
          path: '/module-more-list',
          query: { id, title }
        })
      }
    },

    onFilmList(channel, title) {
      this.$router.push({
        path: '/film-list',
        query: { channel, title }
      })
    },

    onOpenSideBar() {
      this.showSideBar = true
    },

    getChannelName() {
      const target = this.channels.findIndex(channel => channel.id === this.selectedTab)
      return target.title || this.$route.query.title
    },

    goHistory(type) {
      if (this.checkLogin()) {
        this.$router.push({
          path: '/history-list',
          query: { type }
        })
      }
    },

    onLinkToChannel(channel) {
      this.showSideBar = false
      this.onItemDispatch(channel)
    },

    onAppDispatch(item) {
      if (this.checkLogin()) {
        this.onItemDispatch(item)
      }
    }
  }
}
</script>
